package cn.chilemou;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author LiXingShuai
 * @className RabbitGetConsumer
 * @description: TODO
 * @date 2023年04月12日
 * @version: 1.0
 */
public class RabbitGetConsumer {

    private static final String EXCHANGE_NAME ="exchange_demo";
    private static final String ROUTING_KEY ="routingKey_demo";
    private static final String QUEUE_MAME ="queue_demo";

    private static final String IP_ADDRESS ="47.94.171.202";

    private static final int PORT = 5672;

    private static final String USERNAME = "root";
    private static final String PWD = "root";

    /**
     * 是否自动确认
     */
    private static final boolean AUTO_ACK =false;

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername(USERNAME);
        connectionFactory.setPassword(PWD);
        connectionFactory.setVirtualHost("host1");

        Connection connection = connectionFactory.newConnection(new Address[]{new Address(IP_ADDRESS,PORT)});
        Channel channel = connection.createChannel();
        // 主动获取队列中的消息
        GetResponse getResponse = channel.basicGet(QUEUE_MAME,false);
        if (getResponse != null) {
            byte[] bytes = getResponse.getBody();
            String result = new String(getResponse.getBody());
            System.out.println(result);
            TimeUnit.SECONDS.sleep(5);
            channel.basicAck(getResponse.getEnvelope().getDeliveryTag(),false);// 回信儿，已处理
            //channel.basicReject(getResponse.getEnvelope().getDeliveryTag(),true);// 回信儿，单个拒绝 消息标识+是否回到队列中true
            //channel.basicNack(getResponse.getEnvelope().getDeliveryTag(),false,true);// 回信儿，全部拒绝 消息标识+是否回到队列中true
            //channel.basicRecover();// 重新让broker发送未被确认的消息
        }
        //TimeUnit.SECONDS.sleep(10);
        //channel.close();
        channel.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException e) {
                // isHardError 判断是否为connection导致的异常
                if (e.isHardError()){
                    Connection conn = (Connection) e.getReference();
                    if (e.isInitiatedByApplication()){
                        Method method = e.getReason();
                        // ....
                    }
                }else{
                    // 信道原因导致的异常
                    System.out.println("信道结束原因"+e.getReason());
                }
            }
        });
        channel.close(0,"自主关闭信道");// 自定义关闭类型码+关闭信息
        connection.close();
    }
}
